package progress.exa28_3.part1;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemaphoreStudy {

    public static void main(String[] args) {

        Account account = new Account();
        ExecutorService executorService = Executors.newFixedThreadPool(300);

        for(int j=0;j<200;j++){
            executorService.execute(()->{
                for(int i = 0;i<100;i++)
                    account.deposit(100);
            });
        }
        executorService.execute(()->{
            while (true)
                account.getBalance();
        });

    }


    private static class Account {

        //创建写信号量
        private static Semaphore writeSemaphore = new Semaphore(1);

        //创建读信号量
        private static Semaphore readSemaphore = new Semaphore(5);

        private int balance = 0;//余额

        public int getBalance() {
            int res = 0;
            try {
                readSemaphore.acquire();
                res = balance;
                System.out.println("获取余额："+res);
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                readSemaphore.release();
            }
            return res;
        }

        public void deposit(int amount) {
            try{
                writeSemaphore.acquire();//获得许可
                int newBalance = balance+amount;//访问余额
                balance = newBalance;//更新余额
                //Thread.sleep(1000);
            }catch(InterruptedException ex) {

            } finally {
                writeSemaphore.release();//归还信号量
            }
        }

    }
}
